const IO = require("socket.io");
const Model = require("../DB/Model");
module.exports = function(server) {
  const io = IO(server);
  io.on("connection", function(socket) {
    console.log(
      "连接socket------------------------------------------------------"
    );
    socket.on("disconnect", function() {
      console.log("disconnection---------------------------------------------");
    });
    socket.on("sendMsg", async function({ from, to, content }) {
      console.log("接收到客户端发送的消息", content);
      //存入数据库后 广播消息
      const chart_id = [from, to].sort().join("");
      const messageModel = new Model("zhipin.message", {
        from_id: from,
        to_id: to,
        chart_id,
        content,
        isread: 0,
        create_time: Date.now()
      });
      try {
        const result = await messageModel.save();
        const msgs = await Model.find("zhipin.message", {
          from_id: from,
          to_id: to,
          content
        });
        io.emit('receiveMsg',msgs)
      } catch (error) {
        console.log(error);
      }
    });
  });
};
